const express = require('express')
const app = express()
const Vue = require('vue')
const Vue3Compiler = require('@vue/compiler-ssr')  // vue3编译器
const renderer = require('@vue/server-renderer')    // 渲染器

const vueapp = {
  template: `
    <div>
      <h1 @click='add'>Hello, SSR!</h1>
      <ul>
        <li v-for="item in items" :key="item">{{ item }}</li>
      </ul>
    </div>
  `,
  data() {
    return {
      items: ['Item 1', 'Item 2', 'Item 3']
    }
  },
  methods: {
    add() {
      this.items.push(`Item ${this.items.length + 1}`);
    }
  }
}

// 读取vue文件，编译成js代码
vueapp.ssrRender = new Function('require', Vue3Compiler.compile(vueapp.template).code)(require)


app.get('/', async (req, res) => {
  let vapp = Vue.createSSRApp(vueapp)
  let html = await renderer.renderToString(vapp)   // 渲染成html
  const title = 'SSR Demo';
  let ret = `
  <!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>${title}</title>
</head>
<body>
  ${html}
</body>
</html>`
  res.send(ret)

})
app.listen(3000, () => {
  console.log('SSR server is running on port 3000');
})


